import axios from "axios";
import { useLocalStorage } from "@vueuse/core";

import { TOKEN_KEY, RES_DATA_KEY } from "./constants";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";

const token = useLocalStorage(TOKEN_KEY, "");

const router = useRouter;

//异常处理
const errorHandler = {
  401: (msg) => {
    message.error(msg || "没有权限");
  },
  403: (msg) => {
    message.error("登录已过期，请重新登录" || msg);
    token.value = "";
    router.push("/login");
  },
  500: (msg) => {
    message.error(msg || "服务器异常");
  },
};

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || "",
  timeout: 5000,
});

service.interceptors.request.use((config) => {
  if (token.value) {
    config.headers[TOKEN_KEY] = token.value;
  }
  return config;
});

service.interceptors.response.use(
    (res) => {
      const response = res.data;
      const { code, msg } = response;
      const data = response[RES_DATA_KEY];
      if (code === 200) {
        return data;
      }
      errorHandler[code]?.(msg);
      return Promise.reject(data);
    },
    (error) => {
      return Promise.reject(error);
    }
);

const get = (url, params = {}) => {
  return service({
    method: "get",
    url,
    params,
  });
};

const post = (url, data = {}) => {
  return service({
    method: "post",
    url,
    data: data,
  });
};
export const request = {
  get,
  post,
};
